import { useRefs, useWebConfigStore, useUserStore } from '@/stores'
import { useStorage, $http, $tool } from '@/utils'
import { appletlogin, officialLogin } from '@/api/user.js'
const { setUserInfo, setToken, getUserInfo } = useUserStore()

export async function login(cb) {
	const { get } = useStorage()
	let pid = get('PID') || 0
	uni.showLoading({
		title: '登录中...'
	})
	let data = {
		pid: pid
	}
	// #ifdef MP-WEIXIN
	uni.login({
		provider: 'weixin',
		success(e) {
			data.code = e.code
			appletlogin(data).then(res => {
				setToken(res.data.token)
				setUserInfo(res.data.user)
				$tool.toast('登录成功')
				cb()
			})
		}
	})
	// #endif

	// #ifdef H5
	let path = '/pages/index/index'
	const pages = getCurrentPages();
	const prevPage = pages[0];
	path = prevPage.route
	officialLogin({ ...data, page: path }).then(res => {
		location.assign(res.data);
	})
	// #endif
}